package images

import (
	"encoding/json"
	"io"
	"net/http"
	"server/internal/common/biz"
	"server/internal/logic/images"
	"server/internal/svc"
	"server/internal/types"
	"server/internal/utils"

	"github.com/zeromicro/go-zero/rest/httpx"
)

// search image
func SearchHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")

		var req types.SearchImageReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		respChan := make(chan []types.SearchImageResp)
		errChan := make(chan *biz.Error)
		l := images.NewSearchLogic(r.Context(), svcCtx)
		go l.Search(&req, respChan, errChan)
		httpx.Stream(r.Context(), w, func(w io.Writer) bool {
			select {
			case bizErr := <-errChan:
				err := utils.SseFail(w, bizErr)
				if err != nil {
					return false
				}
			case resps := <-respChan:
				if resps == nil || len(resps) == 0 {
					l.Logger.Errorf("search failed, no result")
					err := utils.SseFail(w, biz.ImageSearchNotFoundError)
					if err != nil {
						return false
					}
				} else {
					for _, item := range resps {
						itemStr, _ := json.Marshal(item)
						err := utils.SeeSuccess(w, string(itemStr))
						if err != nil {
							break
						}
					}
				}
			}
			return false
		})
	}
}
